import logging
from django.conf import settings
from storage.rawdata import RawEventDataStorage
from common.es_core.es_interface import es_bulk_insert_interface, es_insert_interface

_LOGGER = logging.getLogger(__name__)


class ESRawEventDataStorage(RawEventDataStorage):
    """
    ElasticSearch 存储器，對 ElasticSearch 存儲流程進行封裝
    """
    def __init__(self, name, cluster='maestro'):
        """
        :param name: ES index name
        """
        super().__init__(name)
        self.index = name
        assert cluster in settings.ES_CLUSTER_CLIENT_URLS
        self.cluster = cluster
        self.batch_buffer = list()

    def save(self, event):
        es_insert_interface(self.index, event, cluster=self.cluster)

    def add_batch(self, events):
        assert isinstance(events, list) or isinstance(events, dict)
        if isinstance(events, list):
            self.batch_buffer.extend(events)
        else:
            self.batch_buffer.append(events)

    def execute_batch(self):
        if not self.batch_buffer:
            return
        self._bulk_save()
        self.batch_buffer.clear()

    def _bulk_save(self):
        es_bulk_insert_interface(self.index, self.batch_buffer, cluster=self.cluster)
